package com.mall.dao;

import com.mall.domain.Role;
import com.mall.domain.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 角色的持久层接口
 *
 * @author :liangY
 * @date : 2021-01-09 10:49
 */
@Repository
public interface IRoleDao {

    /**
     * 查询所有角色
     *
     * @return
     */
    @Results(id = "roleMap",
            value = {
            @Result(id = true, column = "id", property = "id"),
            @Result(column = "id",
                    property = "permissions",
                    many = @Many(select = "com.mall.dao.IPermissionDao.getTree2", fetchType = FetchType.LAZY)
            )
    })
    @Select("select * from tb_role")
    List<Role> findAll();

    /**
     * 查询所有角色
     *
     * @return
     */
    @Results(id = "roleMap2",
            value = {
                    @Result(id = true, column = "id", property = "id"),
                    @Result(column = "id",
                            property = "permissions",
                            many = @Many(select = "com.mall.dao.IPermissionDao.getTree2", fetchType = FetchType.LAZY)
                    )
            })
    @Select("select * from tb_role where id=(" +
            "select role_id from tb_user_role where user_id=#{user_id})")
    Role findOne(@Param("user_id") Integer user_id);

    /**
     * 更新角色
     *
     * @param role 角色实体类
     * @return
     */
    @Update("update tb_role set role_name=#{role_name},role_desc=#{role_desc} where id = #{id}")
    Integer update(Role role);

    /**
     * 添加角色
     *
     * @param role 角色实体类
     * @return
     */
    @Insert("insert into tb_role values(#{id},#{role_name},#{role_desc})")
    @SelectKey(keyColumn = "id", keyProperty = "id", resultType = Integer.class,
            before = false, statement = {"select last_insert_id()"})
    Integer add(Role role);

    /**
     * 删除角色
     *
     * @param id 角色编号
     * @return
     */
    @Delete("delete from tb_role where id = #{id}")
    Integer del(Integer id);
}
